package com.vilynn.learning.schedule;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author weilin.wang
 */
public class ScheduleTest {

    ScheduledExecutorService schedule = Executors.newScheduledThreadPool(2);

    @Test
    public void test(){
        schedule.schedule(() -> {
            System.out.println("test schedule");
        }, 0L, TimeUnit.MILLISECONDS);

        schedule.scheduleAtFixedRate(() -> {
            System.out.println("test schedule");
        }, 0L, 0L, TimeUnit.MILLISECONDS);

        schedule.scheduleWithFixedDelay(() -> {
            System.out.println("test schedule");
        }, 0L, 0L, TimeUnit.MILLISECONDS);


    }

    @Test
    public void schedule(){
        schedule.schedule(() -> {
            System.out.println("test schedule");
        }, 0L, TimeUnit.MILLISECONDS);

    }

    @Test
    public void schedule2() throws ExecutionException, InterruptedException {
        ScheduledFuture<Object> test_schedule = schedule.schedule(() -> {
            System.out.println("test schedule");
            return "12323";
        }, 1000L, TimeUnit.MILLISECONDS);
        Object o = test_schedule.get();
        System.out.println(o);

    }

    @Test
    public void scheduleAtFixedRate(){
        schedule.scheduleAtFixedRate(() -> {
            System.out.println("test schedule");
        }, 0L, 1L, TimeUnit.SECONDS);

    }

    @Test
    public void scheduleWithFixedDelay(){
        schedule.scheduleWithFixedDelay(() -> {
            System.out.println("test schedule");
        }, 0L, 1L, TimeUnit.SECONDS);
    }

    public static void main(String[] args) throws Exception {
        ScheduleTest scheduleTest = new ScheduleTest();
        scheduleTest.scheduleAtFixedRate();
    }

    @Test
    public void test2() throws InterruptedException {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
//        Runnable runnable = new My("2");
        int delay = 3;
        scheduler.schedule(new My("putong"), delay, TimeUnit.SECONDS);
        scheduler.scheduleAtFixedRate(new My("at"), delay, delay, TimeUnit.SECONDS);
        scheduler.scheduleWithFixedDelay(new My("fix"), delay, delay, TimeUnit.SECONDS);
        Thread.sleep(1000 * 10000);
    }

    //    @AllArgsConstructor
    class My implements Runnable {
        public My(String name) {
            this.name = name;
        }

        private String name;

        @Override
        public void run() {
            System.out.println(name + "::: 执行");
        }
    }
}
